package com.by.interceptor;

import com.by.token.TokenTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    TokenTemplate tokenTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头token
        String token = request.getHeader("token");
        if (null == token || "".equals(token)) {
            fail(response,"没有token，无取访问！");
            return false;
        }

        //验证token
        int rs=tokenTemplate.verifyToken(token);
        if(rs==1){
            fail(response,"无效的token");
            return false;
        }else if(rs==2){
            fail(response,"token已过期");
            return false;
        }
        return true;
    }

    void fail(HttpServletResponse response,String msg){
        response.setContentType("application/json;charset=utf-8");
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        pw.write("{\"code\":0,\"msg\":\""+msg+"\"}");
    }
}
